package org.smile.beans.property;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

import org.smile.util.RegExp;

/**
 * 
 * @author strive
 *
 */
public class LikePropertyConverter implements PropertyConverter {
	
	private static final RegExp upperReg=new RegExp("[A-Z]");
	private PropertyDescriptor[] properties;
	/**
	 * 构造涵数
	 * @param c
	 * @throws IntrospectionException
	 */
	public LikePropertyConverter(Class c) throws IntrospectionException{
		properties= Introspector.getBeanInfo(c).getPropertyDescriptors();
	}
	/**
	 * 把map的键转成 bean的 属性
	 */
	public PropertyDescriptor keyToProperty(String name) {
		for(int i=0;i<properties.length;i++){
			String propertyName=properties[i].getName();
			if(propertyName.equalsIgnoreCase(name)||name.replaceAll("\\_", "").equalsIgnoreCase(propertyName)){
				return properties[i];
			}
		}
		return null;
	}
	/**
	 * 把bean的属性转成 map的key
	 */
	public String propertyToKey(PropertyDescriptor property) {
		String propertyName=property.getName();
		String[] upperChars=upperReg.find(propertyName);
		if(upperChars!=null){
			for(int i=0;i<upperChars.length;i++){
				propertyName=propertyName.replaceAll(upperChars[i],"_"+upperChars[i].toLowerCase());
			}
		}
		return propertyName;
	}
}
